<template>
    <el-row>
        <el-col :span="6">
            <el-button type="primary" @click="(save = true)">添加</el-button>
            <el-button type="danger" @click="deleteDepartment">删除</el-button>
            <el-button type="danger" @click="remove()">修改</el-button>


            <div style="margin-top: 2%">
                <el-tree
                        :props="props"
                        :load="loadNode"
                        lazy
                        @current-change="handleCurrentChange">
                </el-tree>
            </div>
        </el-col>
        <el-col :span="6" style="margin-left:25%">
            <div>
                <el-form ref="form" :model="form" :rules="formRules" label-width="80px">
                    <el-form-item label="部门编码" prop="coding">
                        <el-input v-model="form.coding" :placeholder=message.coding></el-input>
                    </el-form-item>
                    <el-form-item label="部门名称" prop="name">
                        <el-input v-model="form.name" :placeholder=message.name></el-input>
                    </el-form-item>

                    <el-form-item label="备注" prop="remark">
                        <el-input type="textarea" v-model="form.remark" :placeholder=message.remark></el-input>
                    </el-form-item>
                    <el-form-item label="上级部门" prop="super">
                        <el-select v-model="form.super" :placeholder=message.super>
                            <el-option
                                    label="最上层部门"
                                    key=0
                                    value=0>
                            </el-option>
                            <el-option
                                    v-for="item in departments"
                                    :label=item.name
                                    :key=item.name
                                    :value=item.id>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="modify('form')">保存</el-button>
                        <el-button type="info" @click="cancel">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-col>
        <el-dialog title="添加通行记录" :visible.sync="save" width="24%">
            <el-form ref="saveForm" label-width="80px" :model="saveForm" :rules="saveRules">
                <el-form-item label="部门编码" prop="coding">
                    <el-input v-model="saveForm.coding"></el-input>
                </el-form-item>
                <el-form-item label="部门名称" prop="name">
                    <el-input v-model="saveForm.name"></el-input>
                </el-form-item>

                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" v-model="saveForm.remark"></el-input>
                </el-form-item>
                <el-form-item label="上级部门" prop="super">
                    <el-select v-model="saveForm.super">
                        <el-option
                                label="最上层部门"
                                key=0
                                value=0>
                        </el-option>
                        <el-option
                                v-for="item in departments"
                                :label=item.name
                                :key=item.name
                                :value=item.id>
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="save = false">取 消</el-button>
              <el-button
                      type="primary"
                      @click="saveDepartment('saveForm')"
              >确 定</el-button
              >
            </span>
        </el-dialog>

    </el-row>
</template>

<script>
    export default {
         data() {
             this.getAll()
            var checkCoding = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('部门编码不能为空'));
                }
                setTimeout(() => {
                    let isTrue = false
                    for (let i=0;i<this.departments.length;i++){
                        if (this.departments[i].coding==value){
                            isTrue = true
                        }
                    }
                    if (window.sessionStorage.getItem("coding")==value) isTrue = false
                        if (isTrue) {
                            callback(new Error('部门编号重复'));
                        } else {
                            callback();
                        }
                }, 10);
            };
            return {
                props: {
                    label: 'name',
                    children: 'zones'
                },
                save: false,
                saveForm: {},
                formRules: {
                    coding: [
                        {trigger: 'change',validator: checkCoding},
                        {message: '请输入数字', pattern: /^[0-9]*$/, trigger: 'change'}
                    ]
                },
                saveRules: {
                    coding: [
                        {trigger: 'change',validator: checkCoding},
                        {message: '请输入数字', pattern: /^[0-9]*$/, trigger: 'change'}
                    ],
                    name: [
                        {required: true, type: 'string', message: '请输入部门名称', trigger: 'blur'}
                    ],
                    remark: [
                        {min: 0, max: 100, message: '长度在 100 个字符以内', trigger: 'change'}
                    ],
                    super: [
                        {required: true, message: '请选择上级部门', trigger: 'blur'},
                    ]
                },
                list:JSON.parse(window.sessionStorage.getItem('list')),
                form: {},
                message: {},
                checkList: [],
                department: [],
                departments: [],
                departmenList: [],
                count: 1
            };
        },
        methods: {
            saveDepartment(saveForm) {
                this.$refs[saveForm].validate((valid) => {
                    if (valid) {
                        const _this = this
                        this.saveForm.super_id = this.saveForm.super
                        this.$confirm('此操作将永久修改数据, 是否继续?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            this.$http.post("user/department/save", this.saveForm).then(function (resp) {
                                if (resp.data.code == 2000) {
                                    _this.$message({
                                            type: 'success',
                                            message: '添加成功!'
                                        }
                                    );
                                    _this.save = false
                                    location.reload()
                                } else {
                                    _this.$message({
                                            type: 'error',
                                            message: resp.data.msg
                                        }
                                    );
                                }

                            })
                        }).catch(() => {
                            this.$message({
                                type: 'info',
                                message: '已取消添加'
                            });
                            this.save = false

                        });
                    } else {
                        this.$message.error('error submit!!')
                        return false;
                    }
                })

            },
            modify(form) {
                this.$refs[form].validate((valid) => {
                    if (valid) {
                        const _this = this
                        if (this.form.super) this.form.super_id = this.form.super
                        _this.$confirm('此操作将永久修改数据, 是否继续?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            if (this.form.id == undefined) {
                                _this.$message({
                                    type: 'error',
                                    message: '请先选择待修改部门'
                                });
                            } else if (this.form.super_id == this.form.id) {
                                _this.$message({
                                    type: 'error',
                                    message: '上级部门错误，已取消修改'
                                });
                            } else {
                                _this.$http.post("user/department/modify", this.form).then(function (resp) {
                                    if (resp.data.code == 2000) {
                                        _this.$message({
                                                type: 'success',
                                                message: '修改成功!'
                                            }
                                        );
                                        location.reload()
                                    } else {
                                        _this.$message({
                                            type: 'error',
                                            message: resp.data.msg
                                        })
                                    }

                                })
                            }
                        }).catch(() => {
                            _this.$message({
                                type: 'info',
                                message: '已取消添加'
                            });
                        });
                    }else {
                        this.$message.error('error submit!!')
                        return false;
                    }
                })

            },

            deleteDepartment() {
                const _this = this
                let isTrue = false
                for (let i=0;i<this.departments.length;i++){
                    if (this.form.id==this.departments[i].super_id) isTrue = true
                }
                _this.$confirm('此操作将永久修改数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if (isTrue==false) {
                        if (_this.form.id == null) {
                            _this.$message({
                                type: 'error',
                                message: '删除失败'
                            });
                        } else {
                            _this.$http.post("user/department/delete", _this.form).then(function (resp) {
                                _this.$message({
                                        type: 'success',
                                        message: '删除成功!'
                                    }
                                );
                                location.reload()
                            })

                        }
                    } else {
                        _this.$message({
                                type: 'error',
                                message: '删除失败!该部门拥有下级部门'
                            }
                        );
                    }
                }).catch(() => {
                    _this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            cancel() {
                this.getAll()
                this.form = {}
            },
            async handleCurrentChange(data) {
                const _this = this
                await this.$http.get("/user/department/getOne?id="+data.id).then(function (resp) {
                    window.sessionStorage.setItem("coding",resp.data.data.coding);
                    _this.form = resp.data.data
                    if (_this.form.department == null){
                        _this.message.super = "最上级部门"
                    } else{
                        _this.message.super = _this.form.department.name
                    }
                })


            },
            remove(data){

                    data = {
                        "id": 14,
                        "coding": 123,
                        "name": "人事部",
                        "remark": "人事部",
                        "super_id": 0,
                        "department": null,
                        "treeList": null
                    }

            },
            loadNode(node, resolve) {
                let department = this.list

                if (node.level === 0) {
                    return resolve(department);
                }
                if (node.level > 3) return resolve([]);
                var hasChild;
                if (node.data.treeList != null) {
                    hasChild = true;
                } else hasChild = false;

                let data;
                if (hasChild) {
                    data = node.data.treeList
                } else {
                    data = [];
                }
                resolve(data);
            },
            getAll() {
                const _this = this
                this.$http.get("user/department/getAll").then(function (resp) {
                    _this.departments = resp.data.data
                    _this.departmentList= resp.data.data
                })
            },
        },
        created() {
            this.getAll()
        }
    };
</script>

<style scoped>

</style>
